import Config from '../utils/Config.js';

/**
 * 卡片管理器
 * 负责卡片的生成、管理和计算逻辑
 */
export default class CardManager {
    constructor(gameManager) {
        this.gameManager = gameManager;
        this.cards = [];
        this.selectedCards = [];
        this.availableNumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
        this.operators = ['+', '-', '×', '÷'];
        this.currentCalculation = [];
    }

    /**
     * 初始化卡片
     */
    initCards() {
        console.log('初始化卡片...');
        this.cards = [];
        this.selectedCards = [];
        this.currentCalculation = [];
        
        // 生成主游戏区域的卡片布局
        this.generateMainCards();
        
        // 生成左侧备选卡片
        this.generateSideCards();
        
        console.log('卡片初始化完成，共生成', this.cards.length, '张卡片');
    }

    /**
     * 生成主游戏区域的卡片
     */
    generateMainCards() {
        // 根据图片显示，主游戏区域有一个不规则的卡片布局
        // 这里创建一个简化的网格布局作为示例
        const rows = 4;
        const cols = 6;
        
        for (let row = 0; row < rows; row++) {
            for (let col = 0; col < cols; col++) {
                // 跳过某些位置创建不规则布局
                if (this.shouldSkipPosition(row, col)) continue;
                
                const card = this.createCard({
                    id: `main_${row}_${col}`,
                    type: 'number',
                    value: this.getRandomNumber(),
                    row: row,
                    col: col,
                    area: 'main'
                });
                
                this.cards.push(card);
            }
        }
    }

    /**
     * 生成左侧备选卡片
     */
    generateSideCards() {
        // 左侧备选区域的卡片
        for (let i = 0; i < 8; i++) {
            const card = this.createCard({
                id: `side_${i}`,
                type: 'number',
                value: this.getRandomNumber(),
                index: i,
                area: 'side'
            });
            
            this.cards.push(card);
        }
    }

    /**
     * 创建卡片对象
     */
    createCard(options) {
        return {
            id: options.id,
            type: options.type,
            value: options.value,
            row: options.row,
            col: options.col,
            index: options.index,
            area: options.area,
            selected: false,
            visible: true,
            x: -1000, // 设置为屏幕外的位置，避免意外显示在左上角
            y: -1000, // 设置为屏幕外的位置，避免意外显示在左上角
            width: Config.CARD.WIDTH,
            height: Config.CARD.HEIGHT
        };
    }

    /**
     * 判断是否跳过某个位置（创建不规则布局）
     */
    shouldSkipPosition(row, col) {
        // 创建一个类似图片中的不规则布局
        const skipPositions = [
            [0, 0], [0, 1], [0, 4], [0, 5],
            [1, 0], [1, 5],
            [3, 0], [3, 1], [3, 4], [3, 5]
        ];
        
        return skipPositions.some(pos => pos[0] === row && pos[1] === col);
    }

    /**
     * 获取随机数字
     */
    getRandomNumber() {
        return this.availableNumbers[Math.floor(Math.random() * this.availableNumbers.length)];
    }

    /**
     * 选择卡片
     */
    selectCard(card) {
        if (!card || !card.visible) return false;
        
        if (card.selected) {
            // 取消选择
            card.selected = false;
            this.selectedCards = this.selectedCards.filter(c => c.id !== card.id);
        } else {
            // 选择卡片
            card.selected = true;
            this.selectedCards.push(card);
        }
        
        console.log('当前选中卡片数量:', this.selectedCards.length);
        return true;
    }

    /**
     * 执行计算
     */
    performCalculation(operator) {
        if (this.selectedCards.length < 2) {
            console.log('需要至少选择两张卡片进行计算');
            return null;
        }
        
        const card1 = this.selectedCards[0];
        const card2 = this.selectedCards[1];
        let result = null;
        
        switch (operator) {
            case '+':
                result = card1.value + card2.value;
                break;
            case '-':
                result = Math.abs(card1.value - card2.value);
                break;
            case '×':
                result = card1.value * card2.value;
                break;
            case '÷':
                if (card2.value !== 0) {
                    result = Math.floor(card1.value / card2.value);
                }
                break;
        }
        
        if (result !== null) {
            // 记录计算过程
            this.currentCalculation.push({
                card1: card1.value,
                operator: operator,
                card2: card2.value,
                result: result
            });
            
            // 移除使用的卡片
            this.removeSelectedCards();
            
            console.log(`计算结果: ${card1.value} ${operator} ${card2.value} = ${result}`);
        }
        
        return result;
    }

    /**
     * 移除选中的卡片
     */
    removeSelectedCards() {
        this.selectedCards.forEach(card => {
            card.visible = false;
            card.selected = false;
        });
        
        this.selectedCards = [];
    }

    /**
     * 检查是否还有有效移动
     */
    hasValidMoves() {
        const visibleCards = this.cards.filter(card => card.visible);
        return visibleCards.length >= 2;
    }

    /**
     * 获取所有卡片
     */
    getAllCards() {
        return this.cards;
    }

    /**
     * 获取选中的卡片
     */
    getSelectedCards() {
        return this.selectedCards;
    }

    /**
     * 获取当前计算历史
     */
    getCalculationHistory() {
        return this.currentCalculation;
    }

    /**
     * 洗牌功能
     */
    shuffle() {
        console.log('执行洗牌...');
        
        // 重新分配可见卡片的数值
        const visibleCards = this.cards.filter(card => card.visible);
        visibleCards.forEach(card => {
            card.value = this.getRandomNumber();
            card.selected = false;
        });
        
        this.selectedCards = [];
        console.log('洗牌完成');
    }

    /**
     * 清除选择
     */
    clearSelection() {
        this.selectedCards.forEach(card => {
            card.selected = false;
        });
        this.selectedCards = [];
        console.log('清除选择');
    }

    /**
     * 更新卡片状态
     */
    update() {
        // 这里可以添加卡片动画或其他更新逻辑
    }
}
